package com.workflow.service.impl;

import java.util.Date;
import java.util.List;

import com.common.util.AbstractManager;
import com.common.util.DateHelper;
import com.common.util.PagerModel;
import com.workflow.bean.Applydeptdetail;
import com.workflow.service.ApplydeptdetailService;

public class ApplydeptdetailServiceImpl extends AbstractManager implements
		ApplydeptdetailService {

	public void addApplydeptdetail(Applydeptdetail applydeptdetail) {
		String hql = "select count(*) from Applydeptdetail ap where ap.applydept.applyno = ?";
		long count = 0;
		count = (Long)this.getHibernateTemplate().find(hql,applydeptdetail.getApplydept().getApplyno()).get(0);
		count %= 1000L;
		
//		Long num = Long.parseLong(DateHelper.dateToStr(new Date(), "yyyyMM"));
//		num *= 1000000L;		
//		num += count;
		
		String applyno = applydeptdetail.getApplydept().getApplyno();
		
		String appdetailno = "BLD-" + applyno.substring(applyno.length()-9,applyno.length()) + count;
		applydeptdetail.setAppdetailno(appdetailno);
		
		this.getHibernateTemplate().save(applydeptdetail);
	}

	@SuppressWarnings("unchecked")
	public List<Applydeptdetail> findAllApplydeptdetail() {
		String hql = "from Applydeptdetail ap group by ap.applydept.applyno order by appdetailno";
		return this.getHibernateTemplate().find(hql);
	}

	public Applydeptdetail findApplydeptdetail(String appdetailno) {
		return (Applydeptdetail) this.getHibernateTemplate().load(Applydeptdetail.class, appdetailno);
	}

	public PagerModel findApplydeptdetailForPager() {
		String hql = "from Applydeptdetail ap group by ap.applydept.applyno order by appdetailno";
		return searchPaginated(hql);
	}

	public PagerModel findApplydeptdetailForPager(String applyno) {
		if(applyno == "") {
			return findApplydeptdetailForPager();
		}
		
		String hql = "from Applydeptdetail ap where ap.applydept.applyno = ? order by appdetailno";
		return searchPaginated(hql,applyno);
	}

	public void removeApplydeptdetail(String appdetailno) {
		Applydeptdetail applydeptdetail = null;
		applydeptdetail = (Applydeptdetail) this.getHibernateTemplate().load(Applydeptdetail.class, appdetailno);
		
		if(applydeptdetail != null) {
			this.getHibernateTemplate().delete(applydeptdetail);
			//TODO
		}
		else {
			throw new RuntimeException("have found no instance with appdetailno = " + appdetailno);
		}
	}

	public void updateApplydeptdetail(Applydeptdetail applydeptdetail) {
		this.getHibernateTemplate().update(applydeptdetail);
	}

}
